makeTable <- function(figureName, effectDataframe, tableDirectory){
  ## Make a subset dataframe and organize it nicely for printing a table
  tw0 <- distinct(effectDataframe[,colnames(effectDataframe)[colnames(effectDataframe)!='model_id']])
  tw0 <- arrange(tw0, match(pmask, unlist(smap)), match(treatment, names(tmap)), match(outcome, levels(effectDataframe$pla_shares)), match(outcome, unlist(omap)))
  tw0$outcome1 <- gsub("Defendant Wins","Deft. Wins",gsub("Settlements","Stlmt.",tw0$outcome))
  mc <- ifelse(!"ciL_mc" %in% colnames(tw0), FALSE, ifelse(is.na(tw0$ciL_mc), FALSE, TRUE))
  
  ## What are the p-values we're using?
  ps <- c(0.001,0.01,0.05)
  if(mc){
    ps <- format(round(ps/tw0$ntests[1],4),scientific = FALSE)
  }
  
  fig.name <- figureName
  
  if(nrow(tw0)>20){
    break.tab <- list("_1" = tw0[seq(1,nrow(tw0)/2),], "_2" = tw0[seq((nrow(tw0)/2)+1, nrow(tw0)),])
  } else {
    break.tab <- list("_A" = tw0)
  }
  names(break.tab) <- paste0(fig.name,names(break.tab))
  rm(tw0)
  
  for(i in names(break.tab)){
    tw <- break.tab[[i]]
    # Create a new dataframe that has what we will write in the table
    
    ## Model numbers
    tp <- as_tibble(matrix(c("",paste0("(",seq(1:nrow(tw)),")")), nrow=1))
    
    ## Effects and standard errors
    for(t in unique(tw$treatment1)){
      efline <- c(round(tw$effect,3))
      efline[which(tw$pval<ps[1])] <- paste0(efline[which(tw$pval<ps[1])],"***")
      efline[which(tw$pval>=ps[1] & tw$pval<ps[2])] <- paste0(efline[which(tw$pval>=ps[1] & tw$pval<ps[2])],"**")
      efline[which(tw$pval>=ps[2] & tw$pval<ps[3])] <- paste0(efline[which(tw$pval>=ps[2] & tw$pval<ps[3])],"*")
      efline <- gsub("-","--",efline)
      efline[which(tw$treatment1!=t)] <- "---"
      efline <- as_tibble(matrix(c(gsub("\n", " ", t), efline), nrow=1))
      seline <- paste0("(",round(tw$se,3),")")
      seline[which(tw$treatment1!=t)] <- ""
      seline <- as_tibble(matrix(c("", seline), nrow=1))
      tp <- bind_rows(tp, efline, seline)
    }
    
    ## Write the model information
    if(any(grepl("Def", tw$outcome))){
      tp <- bind_rows(tp, as_tibble(matrix(c("Outcome", gsub(" Wins","",tw$outcome1)), nrow=1)))
      tp <- bind_rows(tp, as_tibble(matrix(c("", gsub("(Stlmt.|Deft. )","",tw$outcome1)), nrow=1)))
    } else {
      tp <- bind_rows(tp, as_tibble(matrix(c("Outcome", tw$outcome1), nrow=1)))
    }
    tp <- bind_rows(tp, as_tibble(matrix(c("Cases", tw$obs), nrow=1)))
    tp <- bind_rows(tp, as_tibble(matrix(c("Treatment Judges", tw$judges_treat), nrow=1)))
    tp <- bind_rows(tp, as_tibble(matrix(c("Control Judges", tw$judges_control), nrow=1)))
    tp <- bind_rows(tp, as_tibble(matrix(c("Randomization Blocks", rep("\\checkmark", nrow(tw))), nrow=1)))
    tp <- bind_rows(tp, as_tibble(matrix(c("Min. Units/Trt. Arm", rep("5", nrow(tw))), nrow=1)))
    tp <- bind_rows(tp, as_tibble(matrix(c("Appt. Pres. Controls", ifelse(tw$pres_controls==1,"\\checkmark","")), nrow=1)))
    if(any(!is.na(tw$pla_shares))){
      tp <- bind_rows(tp, as_tibble(matrix(c("Pltf. Shares Identity", ifelse(grepl("Don't",tw$pla_shares),"No","Yes")), nrow=1)))
      tp <- bind_rows(tp, as_tibble(matrix(c("Race Coding", ifelse(grepl("w=",tw$mask),"w",ifelse(grepl("p=",tw$mask),"p",""))), nrow=1)))
    }
    
    
    # Break up the subsets
    breaks <- c()
    for(s in names(smap)){
      tmp <- which(grepl(s,tw$mask))
      if(length(tmp) > 0){
        breaks <- c(breaks, max(tmp))
      }
    }
    if(length(breaks)>1){
      breaks <- sort(breaks[seq(1,length(breaks)-1)]+1, decreasing=TRUE)
      for(b in breaks){
        tp <- bind_cols(tp[,seq(1,b)], "", tp[,seq(b+1,ncol(tp))])
      }
    } 
    
    ## Write the LaTeX code
    
    fn <- gsub("[_]A","",paste0(tableDirectory, "/", i, ".tex"))
    
    write_lines("", fn, append = FALSE)
    
    if(nrow(tw)>9){
      write_lines(paste0("\\newpage"), fn, append = TRUE)
      write_lines(paste0("\\begin{landscape}"), fn, append = TRUE)
    } 
    
    write_lines(paste0("\\begin{table}[ht]"), fn, append = TRUE)
    
    ## If more than 14 models, need to make the table smaller.
    if(nrow(tw)>14){
     text.size <- "tiny"
    } else if(nrow(tw)>8){
      text.size <- "scriptsize"
    } else {
      text.size <- "scriptsize"
    }
    
    write_lines(paste0("\\", text.size), fn, append = TRUE)
    write_lines(paste0("\\caption{Results from the models used to estimate the effects in \\Cref{fig:",fig.name,"}}\\label{tab:",fig.name,"}"), fn, append = TRUE)
    
    ## Write the first lines
    write_lines(paste0("\\begin{center}"), fn, append = TRUE)
    write_lines(paste0("\\begin{tabular}{l", paste0(rep("c", ncol(tp)-1), collapse = ""), "}"), fn, append = TRUE)
    write_lines("\\hline\\hline", fn, append = TRUE)
    
    ## Write subset labels
    slabel <- c()
    clabel <- c("0-0")
    for(s in names(smap)){
      nmod.s <- nrow(tw[grepl(s,tw$mask),])
      if(nmod.s > 0){
        slabel <- c(slabel, paste0("\\multicolumn{", nmod.s, "}{c}{", smap[[s]], "}"))
        cn <- as.numeric(str_extract(clabel[length(clabel)],"[-]([0-9]+)$",group=1))+2
        clabel <- c(clabel, paste0(cn,"-",cn+nmod.s-1))
      }
    }
    slabel <- paste0(slabel, collapse = " & & ")
    slabel <- paste0(" & ", slabel, "\\\\")
    slabel <- paste0(slabel, paste0(paste0("\\cline{",clabel[seq(2,length(clabel))],"}"), collapse = ""))
    write_lines(slabel,fn, append = TRUE)
    
    for(r in seq(1,nrow(tp))){
      if(tp$V1[r]=="Outcome"){
        write_lines("\\hline", fn, append = TRUE)
      }
      write_lines(paste0(paste0(tp[r,], collapse = " & "), "\\\\"), fn, append = TRUE)
      if(tp$V2[r] == "(1)"){
        write_lines("\\hline", fn, append = TRUE)
      }
    }
    
    write_lines("\\hline\\hline", fn, append = TRUE)
    write_lines("\\end{tabular}", fn, append = TRUE)
    write_lines("\\end{center}", fn, append = TRUE)
    
    
    ntxt <- paste0("{\\scriptsize \\textit{Notes:} ",
                   ifelse(max(tw$pres_controls) == 1, 
                          "For the appointing president variable, the excluded categories are Reagan and Clinton. ",
                          ""),
                   "All models include district-division-year fixed effects, ",
                   "which we refer to as our ``randomization blocks.'' ",
                   "We also use an adjustment proposed by Lin (2013) for all ", 
                   "control variables (see main text). ",
                   "Standard errors are clustered by judge. ",
                   ifelse(mc, 
                          paste0("To adjust for multiple comparisons, we estimated ",
                                 "the number of independent tests that we conducted ",
                                 "and applied a Bonferroni correction (see the text). ",
                                 "Statistical significance (adjusted for multiple ",
                                 "comparisons) is indicated by stars: * $p$ < ", 
                                 ps[3],", ",
                                 "** $p$ < ", ps[2], " and *** $p$ < ", ps[1], ". "),
                          paste0("Statistical significance is indicated by stars: ",
                                 "* $p$ < 0.05, ** $p$ < 0.01 and *** $p$ < 0.001. ")),
                   ifelse(any(grepl("(=1)", tw$mask)),
                          paste0("``Pltf. Shares Identity'' indicates whether the analysis is on subset of cases ",
                                 "in which the plaintiff(s) share the identity of the treatment judges, or not. ",
                                 "``Race Coding'' indicates which package was used to predict plaintiff race: ``w'' is ",
                                 "\\texttt{wru} and ``p'' is \\texttt{predict race}. For plaintiff gender we use the \\texttt{gender} package."),
                          ""),
                   "}"
    )
    write_lines(ntxt, fn, append = TRUE)
    
    write_lines(paste0("\\end{table}"), fn, append = TRUE)
    
    
    if(nrow(tw)>9){
      write_lines(paste0("\\end{landscape}"), fn, append = TRUE)
    } 
    ## Save csv
    
  }
  
  if(length(break.tab)>1){
    to.write <- ""
    for(i in names(break.tab)){
      fn <- paste0(tableDirectory, "/", i, ".tex")
      to.write <- paste0(to.write, read_file(fn))
      file.remove(fn)
    }
    to.write <- str_split(to.write,"[{]tabular[}]")[[1]]
    to.write[3] <- "\n\n\\vspace{10pt}\n\n\\begin"
    to.write <- paste0(to.write, collapse = "{tabular}")
    write_lines(to.write, gsub("[_][0-9]","",fn), append = FALSE)
    
  }
  
  
}

